<?php
define('DS', DIRECTORY_SEPARATOR);
$buffer	= array();
$sites 	= array(
	'app' => array(
		'controllers',
		'models',
		'views',
		'webroot'
	),
	//'app/plugins/admin' => array(),
	//'app/plugins/api' => array(),
);

if (count($argv) > 1) {
	$languages = $argv;
	unset($languages[0]);
		
	foreach ($languages as $language) {
		echo 'Creating language files '.$language.'...'."\n";
		foreach ($sites as $site => $folders) {
			echo 'Creating language for site '.$site.'...'."\n";
			$languageArray 	= array();
			$buffer = array();
			$codes = array();
			foreach ($folders as $key => $value) {
				getFolders('../'.$site.DS.$value);
			}
			$languageArray = $buffer;
			if (!file_exists('../'.$site.DS.'locale'.DS.strtolower($language).DS.'LC_MESSAGES')) {
				mkdir('../'.$site.DS.'locale'.DS.strtolower($language).DS.'LC_MESSAGES', 0777, TRUE);
			}
			$file = '../'.$site.DS.'locale'.DS.strtolower($language).DS.'LC_MESSAGES'.DS.'default.po';
			$f = fopen($file, 'w');
			foreach ($languageArray as $key=>$value) {
				$stringData = 'msgid "'.$key.'"'."\n";
				$stringData .= 'msgstr "'.$language.':-'.$value.'-"'."\n";
				fwrite($f, $stringData."\n");
			}
			fclose($f);
		}
	}
}

function getFolders($directory) {
	global $buffer;
	$handler = opendir($directory);
	$return = array();
   	while ($file = readdir($handler)) {
		if ($file != "." && $file != "..") {
			if (is_dir($directory.DS.$file)) {
				getFolders($directory.DS.$file);
			} else {
				if (((strtolower(substr($file, strrpos($file, '.')+1)) == 'php') OR (strtolower(substr($file, strrpos($file, '.')+1)) == 'ctp')) AND (strpos($file, '.') !== 0)) {
					$myFile = $directory.DS.$file;
					$fh = fopen($myFile, 'r');
					if (filesize($myFile) > 0) {
						echo 'file found: '.$directory.DS.$file."\n";
						$theData = fread($fh, filesize($myFile));
						// search for translated text
						preg_match_all("/(?<=__\(['\"]).*?(?=['\"]( *, *true)*\))/i", $theData, $matches);
						if (count($matches[0]) > 0) {
							foreach ($matches[0] as $results) {
								$buffer[$results] = $results;
							}
						}
						// search for form data
						$matches = array();
						preg_match_all("/(?<=this->Form->input\(['\"]).*?(?=['\"].*?\))/i", $theData, $matches);
						if (count($matches[0]) > 0) {
							foreach ($matches[0] as $results) {
								$buffer[ucwords(str_replace('_', ' ', $results))] = $results;
							}
						}
					}
				}
			}
		}
	}
}
?>